package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ShipmentTable extends Table {

	private static final String SHIPMENT_INSERT = "INSERT INTO Shipment VALUES (%s, '%s', '%s', %s)";
	private static final String SHIPMENT_DELETE = "DELETE FROM Shipment WHERE sid=%s";
	private static final String SHIPMENT_DISPLAY = "SELECT * FROM Shipment";	
	
	private static final String SHIPMENT_FROM_SID = "SELECT * FROM Shipment WHERE sid=%s";
		
	private static final String SHIPMENT_EXISTS_QUERY = "SELECT * FROM Shipment WHERE sid=%s";
	
	public enum Column
	{
		SID(1, true),
		SUP_NAME(2, false),
		STORE_NAME(3, false),
		DATE(4, false);
		
		private int index;
		private boolean isPrimaryKey;
		
		private String[] columnNames = {
				"sid",
				"supName",
				"storeName",
				"date"};
		
		private Column(int index, boolean isPrimaryKey) 
		{
			this.index = index;
			this.isPrimaryKey = isPrimaryKey;
		}
		
		public int getIndex()
		{
			return index;
		}
		
		public String toString()
		{
			return columnNames[this.ordinal()];
		}

		public boolean isPrimaryKey() {
			return this.isPrimaryKey;
		}
	};
	
	public ShipmentTable()
	{
		super(SHIPMENT_INSERT, SHIPMENT_DELETE, SHIPMENT_DISPLAY, SHIPMENT_EXISTS_QUERY);
	}
	
	public String getStoreNameFromSid(int sid) throws SQLException
	{
		String storeName = null;
		
		String fmtdQuery = String.format(SHIPMENT_FROM_SID, String.valueOf(sid));		
		ResultSet rs = dbCon.executeQuery(fmtdQuery);
		
		if(rs != null)
		{
			if(rs.next())
			{
				storeName = rs.getString(Column.STORE_NAME.getIndex());
			}
			
			rs.close();
		}
		
		return storeName;
	}
	
	public void removeShipmentEntry(int sid) throws SQLException
	{
		String fmtdStatement = String.format(SHIPMENT_DELETE, String.valueOf(sid));
		dbCon.executeStatement(fmtdStatement);
	}

	@Override
	public List<String> getPrimaryKeyValues(List<String> insertValues) {
		List<String> primaryKeyValues = new ArrayList<String>();
		for(Column col : Column.values())
		{
			if(col.isPrimaryKey())
			{	
				primaryKeyValues.add(insertValues.get(col.ordinal()));
			}
		}				
		
		return primaryKeyValues;
	}

	@Override
	public List<String> getColumnNames() {
		Column columns[] = Column.values();
		
		List<String> columnNames = new ArrayList<String>(columns.length);
		for( Column col : columns)
		{
			columnNames.add(col.ordinal(), col.toString());
		}
		return columnNames;
	}

	@Override
	public List<String> getPrimaryKeyColumnNames() {
		Column columns[] = Column.values();
		
		List<String> primaryKeyColumnNames = new ArrayList<String>(columns.length);
		for( Column col : columns)
		{
			if(col.isPrimaryKey())
			{
				primaryKeyColumnNames.add(col.ordinal(), col.toString());
			}
		}
		return primaryKeyColumnNames;
	}
}
